/**
 * 商铺/建筑数据操作API
 * 用于管理绑定到3D模型的商铺数据
 */

import { hospitalDB, StoreData } from '../indexedDB'

export interface CreateStoreRequest {
  attractionId: string
  floorId?: string
  name: string
  business: string
  position: [number, number]
  modelInfo?: {
    meshName: string
    boundingBox?: {
      min: [number, number, number]
      max: [number, number, number]
    }
  }
  description?: string
  contact?: {
    phone?: string
    hours?: string
  }
  status?: 'active' | 'inactive' | 'renovation'
  metadata?: Record<string, any>
}

export interface UpdateStoreRequest extends Partial<CreateStoreRequest> {
  id: string
}

export interface StoreResponse {
  success: boolean
  msg: string
  data?: StoreData
}

export interface StoresListResponse {
  success: boolean
  msg: string
  data?: StoreData[]
}

/**
 * 创建商铺
 */
export const createStoreInfo = async (
  store: CreateStoreRequest
): Promise<StoreResponse> => {
  try {
    const data = await hospitalDB.addStore({
      ...store,
      status: store.status || 'active',
      metadata: store.metadata || {}
    })
    
    return {
      success: true,
      msg: '商铺创建成功',
      data
    }
  } catch (error) {
    console.error('创建商铺失败:', error)
    return {
      success: false,
      msg: '创建商铺失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据景区ID获取商铺列表
 */
export const getStoresByAttraction = async (
  attractionId: string
): Promise<StoresListResponse> => {
  try {
    // 暂时使用示例数据，根据不同景区返回不同商铺
    let data: any[] = []
    
    if (attractionId === 'attraction_1') { // 西湖风景区
      data = [
        {
          id: 'store_1_1',
          name: '西湖龙井茶叶店',
          attractionId: 'attraction_1',
          businessType: 'retail',
          category: '茶叶',
          position: [120.1561, 30.2751],
          status: 'active',
          contact: { phone: '0571-87001234', hours: '8:00-20:00' },
          description: '正宗西湖龙井茶叶专卖',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'store_1_2',
          name: '湖心餐厅',
          attractionId: 'attraction_1',
          businessType: 'dining',
          category: '中餐厅',
          position: [120.1541, 30.2731],
          status: 'active',
          contact: { phone: '0571-87001235', hours: '11:00-21:00' },
          description: '湖景中餐厅，杭帮菜正宗',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    } else if (attractionId === 'attraction_2') { // 雷峰塔景区
      data = [
        {
          id: 'store_2_1',
          name: '雷峰塔纪念品店',
          attractionId: 'attraction_2',
          businessType: 'retail',
          category: '纪念品',
          position: [120.1505, 30.2323],
          status: 'active',
          contact: { phone: '0571-87002234', hours: '8:30-17:30' },
          description: '雷峰塔文化纪念品专卖',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    } else if (attractionId === 'attraction_3') { // 湖滨商业区
      data = [
        {
          id: 'store_3_1',
          name: '星巴克咖啡',
          attractionId: 'attraction_3',
          businessType: 'dining',
          category: '咖啡店',
          position: [120.1616, 30.2604],
          status: 'active',
          contact: { phone: '0571-87003234', hours: '7:00-23:00' },
          description: '国际连锁咖啡品牌',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'store_3_2',
          name: '万象城购物中心',
          attractionId: 'attraction_3',
          businessType: 'retail',
          category: '购物中心',
          position: [120.1596, 30.2574],
          status: 'active',
          contact: { phone: '0571-87003235', hours: '10:00-22:00' },
          description: '大型综合购物中心',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'store_3_3',
          name: '湖滨银泰',
          attractionId: 'attraction_3',
          businessType: 'retail',
          category: '百货商场',
          position: [120.1586, 30.2584],
          status: 'active',
          contact: { phone: '0571-87003236', hours: '10:00-22:00' },
          description: '高端百货商场',
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    }
    
    return {
      success: true,
      msg: '获取商铺列表成功',
      data
    }
  } catch (error) {
    console.error('获取商铺列表失败:', error)
    return {
      success: false,
      msg: '获取商铺列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据楼层ID获取商铺列表
 */
export const getStoresByFloor = async (
  floorId: string
): Promise<StoresListResponse> => {
  try {
    const data = await hospitalDB.getStoresByFloor(floorId)
    return {
      success: true,
      msg: '获取楼层商铺列表成功',
      data
    }
  } catch (error) {
    console.error('获取楼层商铺列表失败:', error)
    return {
      success: false,
      msg: '获取楼层商铺列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 更新商铺信息
 */
export const editStore = async (
  id: string,
  updates: Partial<CreateStoreRequest>
): Promise<StoreResponse> => {
  try {
    // 先获取现有数据
    const existing = await hospitalDB.getStore?.(id)
    if (!existing) {
      return {
        success: false,
        msg: '商铺不存在'
      }
    }
    
    // 合并更新数据
    const updatedData: StoreData = {
      ...existing,
      ...updates,
      id,
      updatedAt: new Date()
    }
    
    await hospitalDB.updateStore(updatedData)
    
    return {
      success: true,
      msg: '商铺更新成功',
      data: updatedData
    }
  } catch (error) {
    console.error('更新商铺失败:', error)
    return {
      success: false,
      msg: '更新商铺失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 删除商铺
 */
export const deleteStore = async (id: string): Promise<StoreResponse> => {
  try {
    await hospitalDB.deleteStore(id)
    return {
      success: true,
      msg: '商铺删除成功'
    }
  } catch (error) {
    console.error('删除商铺失败:', error)
    return {
      success: false,
      msg: '删除商铺失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 预设商业类型选项
 */
export const getBusinessTypes = () => {
  return [
    { label: '餐饮', value: 'restaurant', icon: '🍽️' },
    { label: '咖啡厅', value: 'cafe', icon: '☕' },
    { label: '购物', value: 'shopping', icon: '🛍️' },
    { label: '服装', value: 'clothing', icon: '👕' },
    { label: '电子产品', value: 'electronics', icon: '📱' },
    { label: '书店', value: 'bookstore', icon: '📚' },
    { label: '银行', value: 'bank', icon: '🏦' },
    { label: '药店', value: 'pharmacy', icon: '💊' },
    { label: '美容', value: 'beauty', icon: '💄' },
    { label: '健身', value: 'fitness', icon: '💪' },
    { label: '娱乐', value: 'entertainment', icon: '🎮' },
    { label: '其他', value: 'other', icon: '🏪' }
  ]
}

/**
 * 商铺状态选项
 */
export const getStoreStatusOptions = () => {
  return [
    { label: '营业中', value: 'active', color: '#10b981' },
    { label: '暂停营业', value: 'inactive', color: '#f59e0b' },
    { label: '装修中', value: 'renovation', color: '#ef4444' }
  ]
}